from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from upload.models import FileModel
SERVER_URL = 'http://localhost:8000'

# Create your views here.

def upload_image(request):
    if request.method == 'POST':
        file = request.FILES['image']
        title = request.POST.get('title')
        title = title if title else 'A picture'
        try:
            pic = FileModel.objects.create(title=title, picture=file)
            pic_url = pic.picture

            res = {
                "errno": 0,  # 注意：值是数字，不能是字符串
                "data": {
                    "url": f"{SERVER_URL}/media/{pic_url}",  # 图片 src ，必须
                    "alt": title,  # 图片描述文字，非必须
                    "href": ""  # 图片的链接，非必须
                }
            }
        except Exception as e:
            print(f'--Upload Picture error {e}')
            res = {
                "errno": 1,
                "message": f"失败信息:{e}"
            }
        return JsonResponse(res)
    else:
        return HttpResponse('Hello World')
